package log

import (
	"context"
	"fmt"
	"github.com/olivere/elastic"
)

type LoggerElasticsearch struct {
	pool chan string
}

func (logger *LoggerElasticsearch) Init(host string, port string, index string) {
	logger.pool = make(chan string, 1)
	go logger.Sender(logger.pool, host, port, index)
}

func (logger *LoggerElasticsearch) Log(message string) {
	fmt.Println(message)
	logger.pool <- message
}

func (logger *LoggerElasticsearch)Sender(pool chan string, host string, port string, index string) {
	fmt.Println("func Sender()")
	var message string
	//message = <-pool
	fmt.Println(message)

	var esUrl = "http://" + host + ":" + port
	fmt.Println(esUrl)

	client, errNewClient := elastic.NewClient(elastic.SetURL(esUrl),elastic.SetSniff(false))
	// 对于相对于go客户端，设置了内网IP的es机器，go客户端需要设置SetSniff(false)，禁止嗅探，避免在健康节点列表中维护对go客户端来说无法访问的内网IP
	if errNewClient != nil {
		fmt.Println(errNewClient)
	}
	fmt.Println(esUrl)

	esVersion, errElasticsearchVersion := client.ElasticsearchVersion(esUrl)
	if errElasticsearchVersion != nil {
		fmt.Println(errElasticsearchVersion)
	}
	fmt.Printf("es的版本为%s\n", esVersion)

	// Use the IndexExists service to check if a specified index exists.
	exists, errIndexExists := client.IndexExists(index).Do(context.Background())
	if errIndexExists != nil {
		// Handle error
		fmt.Println(errIndexExists)
	}
	if !exists {
		// Create a new index.
		mapping := `
{
	"settings":{
		"number_of_shards":3,
		"number_of_replicas":2
	},
	"mappings":{
		"doc":{
			"properties":{
				"keyword":{
					"type":"keyword"
				},
				"message":{
					"type":"text",
					"store": true,
					"fielddata": true
				},
                "id":{
                    "type":"long"
                }
			}
		}
	}
}
`
		createIndex, errCreateIndex := client.CreateIndex(index).Body(mapping).IncludeTypeName(true).Do(context.Background())
		if errCreateIndex != nil {
			// Handle error
			fmt.Println(errCreateIndex)
		}
		if !createIndex.Acknowledged {
			// Not acknowledged
		}
	}

	// Index a data (using JSON serialization)

	type Data struct {
		Keyword string `json:"keyword"`
		Message string `json:"message"`
		Id int `json:"id"`
	}

	for {
		message = <-pool
		fmt.Println("ready to send message:" + message)

		data := Data{Keyword: "olivere", Message: message, Id: 0}
		put1, errIndex := client.Index().
			Index(index).
			Type("doc").
			Id("1").
			BodyJson(data).
			Do(context.Background())
		if errIndex != nil {
			// Handle error
			fmt.Println(errIndex)
		}
		fmt.Printf("Indexed data %s to index %s, type %s\n", put1.Id, put1.Index, put1.Type)
		//查询所有文档 curl -v -XGET ip:9200/my_index/doc/_search?q=*
	}


}
